import { memo, useEffect, useState } from "react";
import {
  Modal,
  Select,
  Input,
  Button,
  Tag,
  message,
  Switch,
  Skeleton,
  Cascader,
} from "antd";

import { ExclamationCircleOutlined } from "@ant-design/icons";
import {
  AddCommdityAttributeService,
  DeleteCommodityAttributeService,
  PatchCommodityAttributeService,
} from "@/service";

import { IStore } from "@/store";
import AttributeWrapper from "./style";
import { useDispatch, useSelector } from "react-redux";
import { IDispatch } from "@/store";
const { confirm } = Modal;
interface IProps {
  title: string;
  currentTab: any[];
  getDate: () => void;
}
const Attribute = (props: IProps) => {
  const [addAttribute, setAddAttribute] = useState("");
  const [currentEdit, setCurrentEdit] = useState<any>();
  const [currentEditValue, setCurrentEditValue] = useState<any>("");
  const [test, setTest] = useState<any[]>([]);
  const userStore = useSelector((state: IStore) => state.user);
  const [currentAttribute, setCurrentAttribute] = useState<null | number>(null);
  const handleChange = (value: any[]) => {
    setTest(value);
    setCurrentAttribute(value[value.length - 1]);
  };

  // 添加商品标签属性
  async function AddCommodity() {
    if (!currentAttribute || addAttribute === "") {
      message.info("请先填写添加的商品属性");
      return;
    }
    const res: any = await AddCommdityAttributeService({
      is_parent: currentAttribute,
      name: addAttribute,
      type: props.title,
    });
    message.success(res.msg);
    setTest([]);
    props.getDate();
  }
  useEffect(() => {
    console.log(">= ", props);

    setTest([])
  }, [props])
  // 标签删除
  const preventDefault = (
    e: React.MouseEvent<HTMLElement>,
    item: any,
    itemy: any
  ) => {
    e.preventDefault();
    console.log("=> userStore");
    if (
      userStore.user.department == "" ||
      userStore.user.department.includes("adminSSS")
    ) {
      confirm({
        icon: <ExclamationCircleOutlined />,
        className: "file-modal",
        content: (
          <>
            是否删除 {item.name} 的 {itemy.name} 属性
          </>
        ),
        onOk() {
          DeleteCommodityAttributeService(itemy).then((res: any) => {
            if (res.code === 0) {
              message.info(`${item.name}的 ${itemy.name} 属性删除成功`);
            }
            props.getDate();
          });
        },
        onCancel() {
          message.info(`${item.name}的 ${itemy.name} 属性删除取消`);
        },
      });
    } else {
      message.warning("你没有adminSSS部门的权限，不能删除。");
    }
  };
  // 处理显示和隐藏
  const [toggle, setToggle] = useState(false);
  async function handleToggleDisplayClick(item: any) {
    if (
      userStore.user.department == "" ||
      userStore.user.department.includes("adminSSS")
    ) {
      setToggle(true);
      const res: any = await PatchCommodityAttributeService({
        ...item,
        display: item.display == 1 ? "0" : "1",
      });
      if (res.code === 0) {
        message.success("更新成功！");
        props.getDate();
      } else {
        message.success("更新失败！");
      }
      setTimeout(() => {
        setToggle(false);
      }, 500);
    } else {
      message.warning("你没有adminSSS部门的权限，不能删除。");
    }
  }
  return (
    <AttributeWrapper>
      <header className="flex sm:flex-col md:flex-row gap-1">
        <div>添加属性：</div>
        <Cascader
          style={{ width: 150 }}
          allowClear
          changeOnSelect
          value={test}
          placeholder="需要添加的值"
          onChange={handleChange}
          // attribute
          options={props.currentTab.map((item) => ({
            value: item.id,
            label: item.name,
            children: props.title == "attribute" ? item.children?.map((itemy: any) => ({
              value: itemy.id,
              label: itemy.name,
            })) : []
          }))}
        />
        <Input
          allowClear
          value={addAttribute}
          placeholder="请输入需要添加值"
          onChange={(event) => setAddAttribute(event.currentTarget.value)}
          className="w-56 sm:mx-0 md:mx-1"
        ></Input>
        <Button
          className="w-32"
          type={"primary"}
          onClick={() => AddCommodity()}
        >
          添加
        </Button>
      </header>

      {props?.currentTab.length <= 0 &&
        new Array(5)
          .fill(0)
          .map(() => <Skeleton.Button className="h-16 w-full mt-3" block />)}
      <div className="overflow-y-auto sm:max-h-96 lg:max-h-max">
        {props?.currentTab?.map((item, index) => (
          <div key={item.name} className={"attribute shadow"}>
            <div className="flex w-44 justify-between">
              <div
                onClick={() => {
                  setCurrentEdit(item);
                }}
              >
                {item.id === currentEdit?.id ? (
                  <Input
                    placeholder="请输入修改的值"
                    autoFocus
                    defaultValue={currentEdit.name}
                    onChange={(event) =>
                      setCurrentEditValue(event.currentTarget.value)
                    }
                    onBlur={() => {
                      if (currentEditValue === "") {
                        message.error("修改的值不能为空");
                        setCurrentEdit({});
                        return;
                      }
                      PatchCommodityAttributeService({
                        ...currentEdit,
                        value: currentEditValue,
                      }).then((res: any) => {
                        if (res.data.code === 0) {
                          message.success(res.data.msg);
                          console.log("first 数据更新", res.data);
                          props.getDate();
                        } else {
                          message.error(res.data.msg);
                        }
                        setCurrentEditValue("");
                        setCurrentEdit({});
                      });
                    }}
                  ></Input>
                ) : (
                  <span className="ml-2">{item.name}:</span>
                )}
              </div>
              <Switch
                checkedChildren="关闭"
                unCheckedChildren="开启"
                disabled={toggle}
                defaultChecked={item.display == 1 ? true : false}
                onChange={(flag) => handleToggleDisplayClick(item)}
              ></Switch>
            </div>
            <ul>
              {item?.children?.map((itemy: any) => (
                <li key={itemy.id}>
                  <Tag
                    closable
                    className="text-md close-tag"
                    style={{ padding: "3px 10px" }}
                    onClose={(event) => preventDefault(event, item, itemy)}
                  >
                    {itemy.name}
                  </Tag>
                  {itemy?.children?.map((itemx: any) => {
                    return (
                      <li>
                        <Tag
                          closable
                          className="text-md mt-2  close-tag"
                          style={{ padding: "3px 10px" }}
                          onClose={(event) =>
                            preventDefault(event, item, itemx)
                          }
                        >
                          {itemx.name}
                        </Tag>
                      </li>
                    );
                  })}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </AttributeWrapper>
  );
};

export default Attribute;
